package com.yaoweigroup.community.ui.base;

import java.util.regex.Matcher;
import java.util.regex.Pattern;

import org.apache.http.entity.StringEntity;
import org.json.JSONObject;

import android.app.Activity;
import android.app.Dialog;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.view.KeyEvent;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.EditText;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.lidroid.xutils.HttpUtils;
import com.lidroid.xutils.exception.HttpException;
import com.lidroid.xutils.http.RequestParams;
import com.lidroid.xutils.http.ResponseInfo;
import com.lidroid.xutils.http.callback.RequestCallBack;
import com.lidroid.xutils.http.client.HttpRequest;
import com.yaoweigroup.community.R;
import com.yaoweigroup.community.config.Common;
import com.yaoweigroup.community.config.Urls;
import com.yaoweigroup.community.util.DialogUtil;
import com.yaoweigroup.community.util.IDCard;
import com.yaoweigroup.community.util.JsonUtil;
import com.yaoweigroup.community.util.LogUtil;
import com.yaoweigroup.community.util.UtilHttp;

/**
 * 用户注册
 * 
 * @author xi
 * 
 */
public class RegActivity extends Activity implements OnClickListener {

	private LinearLayout info_ll;
	private LinearLayout code_ll;
	private Button next_btn;
	private RelativeLayout left_rl;

	private TextView getCode_tv;
	private EditText code_et;
	private EditText phone_et;
	private EditText email_et;

	private Dialog dialog, regDialog;
	private Button ok_btn;
	private EditText id_et;
	private EditText address_et;
	private EditText pass_et;
	private EditText name_et;
	private EditText repass_et;

	public final int CODE_SUCCESS = 0x2210;
	public final int CODE_FAIL = CODE_SUCCESS + 1;
	public final int REG_SUCCESS = CODE_SUCCESS + 2;
	public final int REG_FAIL = CODE_SUCCESS + 3;

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);

		int width = this.getWindowManager().getDefaultDisplay().getWidth();
		Common.PROPORTION = width / 320f;
		Common.WIDTH = width;
		setContentView(R.layout.activity_reg);
		email_et = (EditText) findViewById(R.id.email_et);
		address_et = (EditText) findViewById(R.id.address_et);
		id_et = (EditText) findViewById(R.id.id_et);
		ok_btn = (Button) findViewById(R.id.ok_btn);
		ok_btn.setOnClickListener(this);
		next_btn = (Button) findViewById(R.id.next_btn);
		next_btn.setOnClickListener(this);
		info_ll = (LinearLayout) findViewById(R.id.info_ll);
		code_ll = (LinearLayout) findViewById(R.id.code_ll);

		left_rl = (RelativeLayout) findViewById(R.id.left_rl);
		left_rl.setOnClickListener(this);
		getCode_tv = (TextView) findViewById(R.id.getCode_tv);
		getCode_tv.setOnClickListener(this);
		code_et = (EditText) findViewById(R.id.code_et);
		phone_et = (EditText) findViewById(R.id.phone_et);
		pass_et = (EditText) findViewById(R.id.pass_et);
		name_et = (EditText) findViewById(R.id.name_et);
		dialog = DialogUtil.createWaitDialog(this, "获取验证码中..");
		regDialog = DialogUtil.createWaitDialog(this, "注册中..");
		repass_et = (EditText) findViewById(R.id.repass_et);
	}

	private String code = null;
	private String phoneStr = null;

	@Override
	public void onClick(View v) {

		switch (v.getId()) {
		case R.id.next_btn:
			String codeStr = code_et.getText().toString();
			if (code != null && code.equals(codeStr)) {
				info_ll.setVisibility(View.VISIBLE);
				code_ll.setVisibility(View.GONE);
			} else {
				Toast.makeText(this, "验证码错误", 500).show();
			}
			break;
		case R.id.left_rl:
			finish();
			break;
		case R.id.getCode_tv:
			getCode();
			break;
		case R.id.ok_btn:
			reg();
			break;
		}
	}

	/**
	 * 获取验证码
	 */
	private void getCode() {
		phoneStr = phone_et.getText().toString();
		if (phoneStr.length() == 0) {
			Toast.makeText(this, "手机号不能为空!", 500).show();
			return;
		}
		dialog.show();
		HttpUtils http = UtilHttp.getHttpUtils(this);
		RequestParams params = new RequestParams();
		JsonUtil jsonUtil = new JsonUtil();
		jsonUtil.add("phone", phoneStr);
		jsonUtil.add("flag", "zhuce");
		LogUtil.d("wxf", jsonUtil.toString());
		StringEntity enity = null;
		try {
			enity = new StringEntity(jsonUtil.toString());
		} catch (Exception e) {
		}
		params.setContentType("application/json");
		params.setBodyEntity(enity);
		params.setHeader("Accept", "application/json");
		http.send(HttpRequest.HttpMethod.POST, Urls.getAuthCode, params,
				new RequestCallBack<String>() {

					@Override
					public void onSuccess(ResponseInfo<String> responseInfo) {
						LogUtil.d("wxf", "result = " + responseInfo.result);
						try {
							JSONObject obj = new JSONObject(responseInfo.result);
							int state = obj.getInt("state");
							String message = obj.getString("message");
							if (state == 200) {
								code = obj.getString("code");
								handler.sendEmptyMessage(CODE_SUCCESS);
							} else {
								Message msg = handler.obtainMessage();
								msg.obj = message;
								msg.what = CODE_FAIL;
								handler.sendMessage(msg);
							}

						} catch (Exception e) {
							handler.sendEmptyMessage(CODE_FAIL);
						}
					}

					@Override
					public void onFailure(HttpException error, String msg) {
						LogUtil.e("wxf", error.toString());
						handler.sendEmptyMessage(CODE_FAIL);
					}

				});

	}

	/**
	 * 用户注册
	 */
	private void reg() {

		String idStr = id_et.getText().toString();
		String addressStr = address_et.getText().toString();
		String emailStr = email_et.getText().toString();
		String passStr = pass_et.getText().toString();
		String nameStr = name_et.getText().toString();
		String repassStr = repass_et.getText().toString();
		if (passStr.length() == 0 || nameStr.length() == 0) {
			Toast.makeText(this, "用户名 或 密码 不能为空!", 500).show();
			return;
		}
		if(!repassStr.equals(passStr)){
			Toast.makeText(this, "2次输入的密码不一致!", 500).show();
			return;
		}

		regDialog.show();
		HttpUtils http = UtilHttp.getHttpUtils(this);
		RequestParams params = new RequestParams();
		JsonUtil jsonUtil = new JsonUtil();
		jsonUtil.add("UserName", nameStr);
		jsonUtil.add("Password", passStr);
		jsonUtil.add("Email", emailStr);
		jsonUtil.add("Mobile", phoneStr);
		jsonUtil.add("Address", addressStr);
		jsonUtil.add("Identity", idStr);
		LogUtil.d("wxf", jsonUtil.toString());
		StringEntity enity = null;
		try {
			enity = new StringEntity(jsonUtil.toString(), "UTF-8");
		} catch (Exception e) {
		}
		params.setContentType("application/json;charset=utf-8");
		params.setBodyEntity(enity);
		params.setHeader("Accept", "application/json");
		http.send(HttpRequest.HttpMethod.POST, Urls.reg, params,
				new RequestCallBack<String>() {

					@Override
					public void onSuccess(ResponseInfo<String> responseInfo) {
						LogUtil.d("wxf", "result = " + responseInfo.result);
						try {
							JSONObject obj = new JSONObject(responseInfo.result);
							int state = obj.getInt("state");
							String message = obj.getString("message");
							if (state == 200) {
								handler.sendEmptyMessage(REG_SUCCESS);
							} else {
								Message msg = handler.obtainMessage();
								msg.obj = message;
								msg.what = REG_FAIL;
								handler.sendMessage(msg);
							}
						} catch (Exception e) {
							handler.sendEmptyMessage(REG_FAIL);
						}
					}

					@Override
					public void onFailure(HttpException error, String msg) {
						LogUtil.e("wxf", error.toString());
						handler.sendEmptyMessage(REG_FAIL);
					}

				});

	}

	@Override
	public boolean onKeyDown(int keyCode, KeyEvent event) {
		if (keyCode == KeyEvent.KEYCODE_BACK) {

			if (info_ll.getVisibility() == View.VISIBLE) {
				info_ll.setVisibility(View.GONE);
				code_ll.setVisibility(View.VISIBLE);
			} else {
				finish();
			}

		}
		return super.onKeyDown(keyCode, event);
	}

	private String error = "";
	Handler handler = new Handler() {

		public void handleMessage(android.os.Message msg) {

			switch (msg.what) {
			case CODE_SUCCESS:
				dialog.dismiss();
				Toast.makeText(RegActivity.this, "验证码已发送", 500).show();
				break;
			case CODE_FAIL:
				dialog.dismiss();
				error = "验证码失败!";
				if (msg.obj != null)
					error = msg.obj.toString();
				Toast.makeText(RegActivity.this, error, 500).show();

				break;
			case REG_FAIL:
				error = "注册失败!";
				if (msg.obj != null)
					error = msg.obj.toString();
				Toast.makeText(RegActivity.this, error, 500).show();
				regDialog.dismiss();
				break;
			case REG_SUCCESS:
				regDialog.dismiss();
				finish();
				break;
			}
		};
	};

	public boolean isEmail(String email) {
		String str = "^([a-zA-Z0-9_\\-\\.]+)@((\\[[0-9]{1,3}\\.[0-9]{1,3}\\.[0-9]{1,3}\\.)|(([a-zA-Z0-9\\-]+\\.)+))([a-zA-Z]{2,4}|[0-9]{1,3})(\\]?)$";
		Pattern p = Pattern.compile(str);
		Matcher m = p.matcher(email);

		return m.matches();
	}

}
